/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lambaithi;

import Utils.Date;
import Utils.Time;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import thitracnghiem.BoDeThi;
import thitracnghiem.CaThi;
import thitracnghiem.CauHoi;
import thitracnghiem.CauTraLoi;
import thitracnghiem.DeThi;
import thitracnghiem.GiaoVien;
import thitracnghiem.KetQuaThi;
import thitracnghiem.Lop;
import thitracnghiem.MonThi;
import thitracnghiem.SinhVien;

/**
 *
 * @author TienNT
 */
public class XuLy extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String yc = request.getParameter("yc");

        try {
            if (yc.equals("hs_dangnhap")) {
                hs_login(request, response);

            } else if (yc.equals("tinhdiem")) {
                tinhdiem(request, response);

            } else if (yc.equals("login")) {
                login(request, response);
            } else if (yc.equals("quanlycauhoi")) {

                quanLyCauHoi(request, response);

            } else if (yc.equals("xemdiem")) {
                xemDiem(request, response);
            } else if (yc.equals("xembaithi")) {
                xemBaiThi(request, response);
            } else if (yc.equals("themcathi")) {
                themCaThi(request, response);
            } else if (yc.equals("quanlycathi")) {
                quanLyCaThi(request, response);
            } else if (yc.equals("themcauhoi")) {
                themCauHoi(request, response);
            } else if (yc.equals("themlop")) {
                themLop(request, response);
            } else if (yc.equals("xoalop")) {
                xoaLop(request, response);
            } else if (yc.equals("themmonthi")) {
                themMonThi(request, response);
            } else if (yc.equals("xoamonthi")) {
                xoaMonThi(request, response);
            } else if (yc.equals("doipasswordgv")) {
                doiPasswordGV(request, response);
            } else if (yc.equals("doipasswordad")) {
                doiPasswordAD(request, response);
            } else if (yc.equals("themgv")) {
                themGV(request, response);
            } else if (yc.equals("phanquyen")) {
                phanQuyen(request, response);
            }
        } catch (SQLException ex) {
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String url = "";
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if (username != null) {
            username = username.trim();
            username = username.replace("  ", " ");
        }
        if (password != null) {
            password = password.trim();
            password = password.replace("  ", " ");
        }
        if (username != null || !username.equals("") && password != null && !password.equals("")) {
            try {
                GiaoVien.Open();
                GiaoVien gv = GiaoVien.loginSuccessful(username, password);
                GiaoVien.Close();
                if (gv != null) {
                    response.getWriter().println("rntered");
                    session = request.getSession();
                    session.setAttribute("gv", (GiaoVien) gv);

                    url = "/tranggiaovien.jsp";
                    if (gv.getUsername().equals("admin")) {
                        url = "/trangad.jsp";
                    }
                } else {
                    url = "/login.jsp";
                }
                RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
                dispatcher.forward(request, response);
            } catch (Exception ex) {
                response.getWriter().println("exception");
                Logger.getLogger(XuLy.class.getName()).log(Level.SEVERE, null, ex);
                response.sendError(404);
                return;
                /*url = "/login.jsp";
                 RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
                 dispatcher.forward(request, response);*/
            }
        }
    }

    void quanLyCauHoi(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        HttpSession session = request.getSession();
        String url = "";
        String tb = "";
        String chonMonThi = request.getParameter("monthi");
        if (chonMonThi != null) {
            session.setAttribute("monthichocauhoi", chonMonThi);
        }
        String monThi = (String) session.getAttribute("monthichocauhoi");
        GiaoVien gv = (GiaoVien) session.getAttribute("gv");
        if (gv == null) {
            response.sendError(403);
            return;
        }

        //hoan tat sua cau hoi
        String hoanTatSuaCauHoi = request.getParameter("hoantatsuacauhoi");
        if (hoanTatSuaCauHoi != null && !hoanTatSuaCauHoi.equals("Thoat")) {
            String cauHoiDaSua = request.getParameter("cauhoidasua");
            if (cauHoiDaSua != null) {
                cauHoiDaSua = cauHoiDaSua.replace("  ", " ");
                cauHoiDaSua = cauHoiDaSua.trim();
            }

            String cauTraLoiDaSua = request.getParameter("cautraloidasua");
            if (cauTraLoiDaSua != null) {
                cauTraLoiDaSua = cauTraLoiDaSua.replace("  ", " ");
                cauTraLoiDaSua = cauTraLoiDaSua.replace("///", "//");
                cauTraLoiDaSua = cauTraLoiDaSua.trim();
                if (cauTraLoiDaSua.length() >= 2) {
                    if (cauTraLoiDaSua.substring(0, 2).equals("//")) {
                        if (cauTraLoiDaSua.length() > 2) {
                            cauTraLoiDaSua = cauTraLoiDaSua.substring(2, cauTraLoiDaSua.length() - 1);
                        } else {
                            cauTraLoiDaSua = "";
                        }
                    }
                }
            }
            String dapAnDaSua = request.getParameter("dapandasua");
            if (dapAnDaSua != null) {
                dapAnDaSua = dapAnDaSua.replace("  ", " ");
                dapAnDaSua = dapAnDaSua.trim();
            }
            try {
                Integer.parseInt(dapAnDaSua);
            } catch (Exception e) {
                tb = "du lieu khong hop le";
                url = "/suacauhoi.jsp?tb=" + tb + "<br>";
                RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
                dispatcher.forward(request, response);
            }
            if (cauHoiDaSua != null && dapAnDaSua != null && cauTraLoiDaSua != null
                    && !cauHoiDaSua.equals("") && !dapAnDaSua.equals("") && !cauTraLoiDaSua.equals("")) {
                CauHoi ch1 = (CauHoi) session.getAttribute("cauhoicansua");
                try {
                    CauHoi.Open();
                    CauTraLoi.Open();
                    CauHoi ch2 = new CauHoi(ch1.getMaCauHoi(), ch1.getMaMonThi(), cauHoiDaSua, cauTraLoiDaSua, Integer.parseInt(dapAnDaSua));
                    //session.removeAttribute("cauhoicansua");

                    if (ch2.isValid() && CauHoi.isDifferent(ch1, ch2) && ch2.updateCauHoi() != 0) {
                        tb = "sua thanh cong";
                    } else {
                        tb = "sua that bai";
                    }

                    CauTraLoi.Close();
                    CauHoi.Close();
                } catch (Exception e) {
                    tb = "sua that bai";

                    url = "/quanlycauhoi.jsp?tb=" + tb + "<br>";
                    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
                    dispatcher.forward(request, response);
                }
            } else {
                tb = "du lieu sai";
                url = "/quanlycauhoi.jsp?tb=" + tb + "<br>";
                RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
                dispatcher.forward(request, response);
            }
        }
        //hoan tat sua cau hoi - end

        //Xoa cau hoi
        String xoacauhoi = request.getParameter("xoacauhoi");
        if (xoacauhoi != null) {
            try {
                CauHoi.Open();
                CauTraLoi.Open();

                if (CauHoi.isDeleable(xoacauhoi)) {
                    if (CauHoi.delCauHoi(xoacauhoi) != 0) {
                        tb = "xoa thanh cong";
                    }
                } else {
                    tb = "xoa that bai";
                }
                CauTraLoi.Close();
                CauHoi.Close();
            } catch (Exception e) {
                tb = "xoa co loi";
                url = "/quanlycauhoi.jsp?tb=" + tb + "<br>";
                RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
                dispatcher.forward(request, response);
            }
        }
        //Xoa cau hoi - end

        //Sua cau hoi
        String suacauhoi = request.getParameter("suacauhoi");
        if (suacauhoi != null) {
            try {
                CauHoi.Open();
                CauTraLoi.Open();
                CauHoi ch = CauHoi.getCauHoi(suacauhoi);
                CauTraLoi.Close();
                CauHoi.Close();
                if (ch != null) {
                    session.setAttribute("cauhoicansua", ch);
                    url = "/suacauhoi.jsp";
                    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
                    dispatcher.forward(request, response);
                }
            } catch (Exception e) {
                tb = "yeu cau sua ko the thuc hien";
                url = "/quanlycauhoi.jsp?tb=" + tb + "<br>";
                RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
                dispatcher.forward(request, response);
            }
        }
        //Sua cau hoi - end

        //lay danh sach cau hoi
        StringBuilder s = null;
        try {
            s = CauHoi.getViewDSCauHoi(monThi);
        } catch (Exception e) {
            tb = "load danh sach mon thi that bai";
            url = "/quanlycauhoi.jsp?tb=" + tb + "<br>";
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
            dispatcher.forward(request, response);
        }
        session.setAttribute("dscauhoi", s);
        //lay danh sach cau hoi - end

        url = "/quanlycauhoi.jsp?tb=" + tb + "<br>";
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
        dispatcher.forward(request, response);
    }

    void themCauHoi(HttpServletRequest request, HttpServletResponse response) throws SQLException, ServletException, IOException {
        //hoan tat them cau hoi
        HttpSession session = request.getSession();
        String tb = "";
        String url = "";
        String mamonthi = request.getParameter("mamonthi");
        if (mamonthi != null) {
            session.setAttribute("monthithemcauhoi", mamonthi);
            mamonthi = mamonthi.replace("  ", " ");
            mamonthi = mamonthi.trim();
        }
        String cauhoi = request.getParameter("cauhoi");
        if (cauhoi != null) {
            cauhoi = cauhoi.replace("  ", " ");
            cauhoi = cauhoi.trim();
            response.getWriter().println(cauhoi);
        }
        String cautraloi = request.getParameter("cautraloi");
        if (cautraloi != null) {
            cautraloi = cautraloi.replace("  ", " ");
            cautraloi = cautraloi.replace("///", "//");
            cautraloi = cautraloi.trim();
            if (cautraloi.length() >= 2) {
                if (cautraloi.substring(0, 2).equals("//")) {
                    if (cautraloi.length() > 2) {
                        cautraloi = cautraloi.substring(2, cautraloi.length() - 1);
                    } else {
                        cautraloi = "";
                    }
                }
            }
        }
        String dapan = request.getParameter("dapan");
        if (dapan != null) {
            dapan = dapan.replace("  ", " ");
            dapan = dapan.trim();
        }
        try {
            Integer.parseInt(dapan);
        } catch (Exception e) {
            tb = "du lieu khong hop le";
            url = "/themcauhoi.jsp?tb=" + tb + "<br>";
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
            dispatcher.forward(request, response);
        }
        //dieu kien cua dap an
        if (mamonthi == null || cauhoi == null || cautraloi == null || dapan == null
                || mamonthi.equals("") || cauhoi.equals("") || cautraloi.equals("") || dapan.equals("")
                || Integer.parseInt(dapan) > 25) {
            tb = "du lieu khong hop le";
        } else {
            try {
                CauHoi.Open();
                CauTraLoi.Open();
                CauHoi ch = new CauHoi(CauHoi.genMaCauHoi(mamonthi), mamonthi, cauhoi, cautraloi, Integer.parseInt(dapan));
                if (ch.isValid()) {
                    ch.insCauHoi();
                    tb = "them cau hoi thanh cong";
                } else {
                    tb = "cau hoi ko hop le";
                }
                CauTraLoi.Close();
                CauHoi.Close();

            } catch (Exception e) {
                tb = "them cau hoi co loi";
                CauTraLoi.Close();
                CauHoi.Close();
                url = "/themcauhoi.jsp?tb=" + tb + "<br>";
                RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
                dispatcher.forward(request, response);
            }
        }

        url = "/themcauhoi.jsp?tb=" + tb + "<br>";
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
        dispatcher.forward(request, response);
        //hoan tat them cau hoi - end
    }

    void xemDiem(HttpServletRequest request, HttpServletResponse response) throws SQLException, ServletException, IOException {
        HttpSession session = request.getSession();
        session.removeAttribute("dsdiemtheolop");
        String tb = "";
        String url = "";
        String monThi = request.getParameter("monthi");
        String lop = request.getParameter("lop");
        String lanThi = request.getParameter("lanthi");
        if (lanThi != null) {
            lanThi = lanThi.replace("  ", " ");
            lanThi = lanThi.trim();
        }
        if (monThi == null || lop == null || lanThi == null || lanThi.equals("") || Float.isNaN(Float.parseFloat(lanThi))) {
            tb = "du lieu ko hop le";
        } else {
            try {
                SinhVien.Open();
                KetQuaThi.openDatabase();
                StringBuilder s = Lop.getDiemTheoDSLop(lop, monThi, Integer.parseInt(lanThi));
                session.setAttribute("dsdiemtheolop", s);
                KetQuaThi.closeDatabase();
                SinhVien.Close();
            } catch (Exception e) {
                tb = "co loi";
            }
        }
        url = "/xemdiem.jsp?tb=" + tb + "<br>";
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
        dispatcher.forward(request, response);
    }

    void xemBaiThi(HttpServletRequest request, HttpServletResponse response) throws SQLException, ServletException, IOException {
        HttpSession session = request.getSession();
        String tb = "";
        String url = "";
        String maSV = request.getParameter("masv");
        String monThi = request.getParameter("monthi");
        String lanThi = request.getParameter("lanthi");
        if (maSV != null) {
            maSV = maSV.trim();
            maSV = maSV.replace("  ", " ");
        }
        if (monThi != null) {
            monThi = monThi.trim();
            monThi = monThi.replace("  ", " ");
        }
        if (lanThi != null) {
            lanThi = lanThi.trim();
            lanThi = lanThi.replace("  ", " ");
        }
        try {
            Integer.parseInt(lanThi);
        } catch (Exception e) {
            tb = "thong tin khong hop le";
            url = "/xembaithi.jsp?tb=" + tb + "<br>";
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
            dispatcher.forward(request, response);
            return;
        }
        if (maSV == null || maSV.equals("") || monThi == null || monThi.equals("") || lanThi == null || lanThi.equals("")) {
            tb = "thong tin khong hop le";
        } else {

            StringBuilder ms = new StringBuilder();
            KetQuaThi.openDatabase();
            ms = KetQuaThi.getBaiThi(maSV, monThi, Integer.parseInt(lanThi));
            if (ms != null) {
                tb = "lay bai thi thanh cong";
            }
            KetQuaThi.closeDatabase();
            session.setAttribute("baithi", ms);
        }
        url = "/xembaithi.jsp?tb=" + tb + "<br>";
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
        dispatcher.forward(request, response);

    }

    void themCaThi(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String url = "";
        String tb = "";
        if (request.getParameter("xacnhan") != null && !request.getParameter("xacnhan").equals("Khong")) {
            String monThi = request.getParameter("mamonthi");
            String lop = request.getParameter("lop");
            String lanThi = request.getParameter("lanthi");
            String ngayThi = request.getParameter("ngaythi");
            String tgBatDau = request.getParameter("tgbatdau");
            String tgKetThuc = request.getParameter("tgketthuc");
            String soCauHoi = request.getParameter("socauhoi");
            if (monThi != null) {
                monThi = monThi.trim();
                monThi = monThi.replace("  ", " ");
            }
            if (lop != null) {
                lop = lop.trim();
                lop = lop.replace("  ", " ");
            }
            if (lanThi != null) {
                lanThi = lanThi.trim();
                lanThi = lanThi.replace("  ", " ");
            }
            if (ngayThi != null) {
                ngayThi = ngayThi.trim();
                ngayThi = ngayThi.replace("  ", " ");
            }
            if (tgBatDau != null) {
                tgBatDau = tgBatDau.trim();
                tgBatDau = tgBatDau.replace("  ", " ");
            }
            if (tgKetThuc != null) {
                tgKetThuc = tgKetThuc.trim();
                tgKetThuc = tgKetThuc.replace("  ", " ");
            }
            if (soCauHoi != null) {
                soCauHoi = soCauHoi.trim();
                soCauHoi = soCauHoi.replace("  ", " ");
            }
            try {
                Integer.parseInt(lanThi);

            } catch (Exception e) {
                tb = "du lieu khong hop le";
                url = "/themcathi.jsp?tb=" + tb + "<br>";
                RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
                dispatcher.forward(request, response);
            }
            if (monThi == null || monThi.equals("") || lop == null || lop.equals("") || lanThi == null
                    || lanThi.equals("") || ngayThi == null || ngayThi.equals("") || tgBatDau == null
                    || tgBatDau.equals("") || tgKetThuc == null || tgKetThuc.equals("") || soCauHoi == null
                    || soCauHoi.equals("") || Date.parseDate(ngayThi) == null || Time.parseTime(tgBatDau) == null
                    || Time.parseTime(tgKetThuc) == null) {
                tb = "du lieu khong hop le";
                url = "/themcathi.jsp?tb=" + tb + "<br>";
                RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
                dispatcher.forward(request, response);
            } else {
                CaThi ct = new CaThi(lop, monThi, Integer.parseInt(lanThi), Date.parseDate(ngayThi).toString(),
                        Time.parseTime(tgBatDau).toString(),
                        Time.parseTime(tgKetThuc).toString(),
                        Integer.parseInt(soCauHoi), 0);
                try {
                    CaThi.Open();
                    if (ct.isValid()) {

                        if (ct.insCaThi() > 0) {
                            tb = "them ca thi thanh cong";
                        } else {
                            tb = "them ca thi that bai";
                        }
                        CaThi.Close();
                    } else {
                        tb = "ca thi khong hop le";
                    }
                } catch (Exception e) {
                    tb = "them ca thi co loi";
                }
            }
        }
        url = "/themcathi.jsp?tb=" + tb + "<br>";
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
        dispatcher.forward(request, response);

    }

    void quanLyCaThi(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String url = "";
        String tb = "";

        //xoa ca thi
        String xoaCaThi = request.getParameter("xoacathi");
        if (xoaCaThi != null) {
            xoaCaThi = xoaCaThi.trim();
            xoaCaThi = xoaCaThi.replace("  ", " ");

            if (xoaCaThi.equals("")) {
                tb = "du lieu khong hop le";
                url = "/quanlycathi.jsp?tb=" + tb + "<br>";
                RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
                dispatcher.forward(request, response);
            }
            try {
                Integer.parseInt(xoaCaThi);
            } catch (Exception e) {
                tb = "du lieu khong hop le";
                url = "/quanlycathi.jsp?tb=" + tb + "<br>";
                RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
                dispatcher.forward(request, response);
            }
            try {
                CaThi.Open();
                CaThi.delCaThi(Integer.parseInt(xoaCaThi));
                CaThi.Close();
            } catch (Exception e) {

                tb = "xoa ca thi that bai";
                url = "/quanlycathi.jsp?tb=" + tb + "<br>";
                RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
                dispatcher.forward(request, response);
            }
            tb = "xoa ca thi thanh cong";
            url = "/quanlycathi.jsp?tb=" + tb + "<br>";
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
            dispatcher.forward(request, response);
        }
        //xoa ca thi - end

        //sua ca thi
        String suaCaThi = request.getParameter("suacathi");
        if (suaCaThi != null) {
            suaCaThi = suaCaThi.trim();
            suaCaThi = suaCaThi.replace("  ", " ");

            if (suaCaThi.equals("")) {
                tb = "du lieu khong hop le";
                url = "/quanlycathi.jsp?tb=" + tb + "<br>";
                RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
                dispatcher.forward(request, response);
            }
            try {
                Integer.parseInt(suaCaThi);
            } catch (Exception e) {
                tb = "du lieu khong hop le";
                url = "/quanlycathi.jsp?tb=" + tb + "<br>";
                RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
                dispatcher.forward(request, response);
            }
            try {
                CaThi.Open();
                CaThi cathi1 = CaThi.getCaThi(Integer.parseInt(suaCaThi));
                CaThi.Close();
                session.setAttribute("cathicansua", cathi1);
                url = "/suacathi.jsp";
                RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
                dispatcher.forward(request, response);
            } catch (Exception e) {
                tb = "yeu cau sua ca thi khong hop le";
                url = "/quanlycathi.jsp?tb=" + tb + "<br>";
                RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
                dispatcher.forward(request, response);
            }

        }
        //sua ca thi - end

        //hoan tat sua ca thi
        if (!request.getParameter("hoantatsuacathi").equals("Khong")) {
            String monThi = request.getParameter("mamonthi");
            String lop = request.getParameter("lop");
            String lanThi = request.getParameter("lanthi");
            String ngayThi = request.getParameter("ngaythi");
            String tgBatDau = request.getParameter("tgbatdau");
            String tgKetThuc = request.getParameter("tgketthuc");
            String soCauHoi = request.getParameter("socauhoi");
            if (monThi != null) {
                monThi = monThi.trim();
                monThi = monThi.replace("  ", " ");
            }
            if (lop != null) {
                lop = lop.trim();
                lop = lop.replace("  ", " ");
            }
            if (lanThi != null) {
                lanThi = lanThi.trim();
                lanThi = lanThi.replace("  ", " ");
            }
            if (ngayThi != null) {
                ngayThi = ngayThi.trim();
                ngayThi = ngayThi.replace("  ", " ");
            }
            if (tgBatDau != null) {
                tgBatDau = tgBatDau.trim();
                tgBatDau = tgBatDau.replace("  ", " ");
            }
            if (tgKetThuc != null) {
                tgKetThuc = tgKetThuc.trim();
                tgKetThuc = tgKetThuc.replace("  ", " ");
            }
            if (soCauHoi != null) {
                soCauHoi = soCauHoi.trim();
                soCauHoi = soCauHoi.replace("  ", " ");
            }
            try {
                Integer.parseInt(lanThi);
            } catch (Exception e) {
                tb = "du lieu khong hop le exception";
                url = "/quanlycathi.jsp?tb=" + tb + "<br>";
                RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
                dispatcher.forward(request, response);
            }
            if (monThi == null || monThi.equals("") || lop == null || lop.equals("") || lanThi == null
                    || lanThi.equals("") || ngayThi == null || ngayThi.equals("") || tgBatDau == null
                    || tgBatDau.equals("") || tgKetThuc == null || tgKetThuc.equals("") || soCauHoi == null
                    || soCauHoi.equals("") || Date.parseDate(ngayThi) == null || Time.parseTime(tgBatDau) == null
                    || Time.parseTime(tgKetThuc) == null) {
                tb = "du lieu khong hop le ";
                url = "/quanlycathi.jsp?tb=" + tb + "<br>";
                RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
                dispatcher.forward(request, response);
            } else {
                CaThi ct = new CaThi(lop, monThi, Integer.parseInt(lanThi), Date.parseDate(ngayThi).toString(),
                        Time.parseTime(tgBatDau).toString(),
                        Time.parseTime(tgKetThuc).toString(),
                        Integer.parseInt(soCauHoi), 0);
                try {
                    CaThi temp = (CaThi) request.getSession().getAttribute("cathicansua");
                    if (temp != null && CaThi.isDifferent(ct, temp) && ct.isValid()) {
                        CaThi.Open();
                        CaThi.updateCaThi(temp.getID(), ct);
                        CaThi.Close();
                    }
                } catch (Exception e) {
                    tb = "them ca thi co loi";
                }
            }
            url = "/quanlycathi.jsp?tb=" + tb + "<br>";
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
            dispatcher.forward(request, response);
        }

        //hoan tat sua ca thi - end
    }

    void themLop(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String tb = "";
        String url = "";
        String lop = request.getParameter("lop");
        if (lop != null) {
            lop = lop.trim();
            lop = lop.replace("  ", " ");
        }
        if (lop == null || lop.length() > 15 || lop.equals("")) {
            tb = "du lieu khong hop le";
            url = "/themlop.jsp?tb=" + tb;
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
            dispatcher.forward(request, response);
        }
        try {
            Lop.Open();
            if (Lop.insLop(lop) > 0) {
                tb = "them thanh cong";
            } else {
                tb = "them that bai";
            }
            Lop.Close();
        } catch (Exception e) {
            tb = "them that bai";
            url = "/themlop.jsp?tb=" + tb;
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
            dispatcher.forward(request, response);
        }
        url = "/themlop.jsp?tb=" + tb;
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
        dispatcher.forward(request, response);
    }

    void xoaLop(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String url = "";
        String tb = "";
        String lop = request.getParameter("lop");
        if (lop != null) {
            try {
                Lop.Open();
                if (Lop.delLop(lop) > 0) {
                    tb = "xoa thanh cong";
                } else {
                    tb = "xoa that bai";
                }
                Lop.Close();
            } catch (Exception e) {
                tb = "xoa that bai";
                url = "/xoalop.jsp?tb=" + tb;
                RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
                dispatcher.forward(request, response);
            }
            url = "/xoalop.jsp?tb=" + tb;
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
            dispatcher.forward(request, response);
        }
    }

    void themMonThi(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String tb = "";
        String url = "";
        String maMonThi = request.getParameter("mamonthi");
        String tenMonThi = request.getParameter("tenmonthi");
        if (maMonThi != null) {
            maMonThi = maMonThi.trim();
            maMonThi = maMonThi.replace("  ", " ");
        }
        if (tenMonThi != null) {
            tenMonThi = tenMonThi.trim();
            tenMonThi = tenMonThi.replace("  ", " ");
        }
        if (maMonThi == null || tenMonThi == null || maMonThi.equals("") || tenMonThi.equals("")
                || maMonThi.length() > 15 || tenMonThi.length() > 40) {
            tb = "du lieu khong hop le";
            url = "/themmonthi.jsp?tb=" + tb;
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
            dispatcher.forward(request, response);
        }
        try {
            MonThi.Open();
            if (MonThi.insMonThi(maMonThi, tenMonThi) > 0) {
                tb = "them mon thi thanh cong";
            } else {
                tb = "them mon thi that bai";
            }
            MonThi.Close();
        } catch (Exception e) {
            tb = "them mon thi that bai";
            url = "/themmonthi.jsp?tb=" + tb;
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
            dispatcher.forward(request, response);
        }
        url = "/themmonthi.jsp?tb=" + tb;
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
        dispatcher.forward(request, response);
    }

    void xoaMonThi(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String url = "";
        String tb = "";
        String lop = request.getParameter("mamonthi");
        if (lop != null) {
            try {
                MonThi.Open();
                if (MonThi.delMonThi(lop) > 0) {
                    tb = "xoa thanh cong";
                } else {
                    tb = "xoa that bai";
                }
                MonThi.Close();
            } catch (Exception e) {
                tb = "xoa that bai";
                url = "/xoamonthi.jsp?tb=" + tb;
                RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
                dispatcher.forward(request, response);
            }
            url = "/xoamonthi.jsp?tb=" + tb;
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
            dispatcher.forward(request, response);
        }
    }

    void doiPasswordGV(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        GiaoVien gv = (GiaoVien) request.getSession().getAttribute("gv");
        if (gv == null) {
            response.sendError(403);
            return;
        }
        String url = "";
        String tb = "";
        String passwordCu = request.getParameter("passwordcu");
        String passwordMoi = request.getParameter("passwordmoi");
        if (passwordCu != null) {
            passwordCu = passwordCu.trim();
            passwordCu = passwordCu.replace("  ", " ");
        }
        if (passwordMoi != null) {
            passwordMoi = passwordMoi.trim();
            passwordMoi = passwordMoi.replace("  ", " ");
        }
        if (passwordCu == null || passwordMoi == null || !passwordCu.equals(gv.getPassword()) || passwordCu.equals("")
                || passwordMoi.equals("") || passwordMoi.length() > 32) {
            tb = "du lieu khong hop le";
            url = "/doipasswordgv.jsp?tb=" + tb;
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
            dispatcher.forward(request, response);
        }
        try {
            GiaoVien.Open();
            if (GiaoVien.changePassword(gv.getID(), passwordMoi) > 0) {
                tb = "doi password thanh cong";
                url = "/login.jsp";
                RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
                dispatcher.forward(request, response);
            } else {
                tb = "doi password that bai";
                url = "/doipasswordad.jsp?tb=" + tb;
                RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
                dispatcher.forward(request, response);
            }
            GiaoVien.Close();
        } catch (Exception e) {
            tb = "doi password that bai exception";
            url = "/doipasswordgv.jsp?tb=" + tb;
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
            dispatcher.forward(request, response);
        }
        url = "/doipasswordgv.jsp?tb=" + tb;
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
        dispatcher.forward(request, response);
    }

    void doiPasswordAD(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        GiaoVien gv = (GiaoVien) request.getSession().getAttribute("gv");
        if (gv == null) {
            response.sendError(403);
            return;
        }
        String url = "";
        String tb = "";
        String passwordCu = request.getParameter("passwordcu");
        String passwordMoi = request.getParameter("passwordmoi");
        if (passwordCu != null) {
            passwordCu = passwordCu.trim();
            passwordCu = passwordCu.replace("  ", " ");
        }
        if (passwordMoi != null) {
            passwordMoi = passwordMoi.trim();
            passwordMoi = passwordMoi.replace("  ", " ");
        }
        if (passwordCu == null || passwordMoi == null || !passwordCu.equals(gv.getPassword()) || passwordCu.equals("")
                || passwordMoi.equals("") || passwordMoi.length() > 32) {
            tb = "du lieu khong hop le";
            url = "/doipasswordad.jsp?tb=" + tb;
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
            dispatcher.forward(request, response);
        }
        try {
            GiaoVien.Open();
            if (GiaoVien.changePassword(gv.getID(), passwordMoi) > 0) {
                tb = "doi password thanh cong";
                url = "/login.jsp";
                RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
                dispatcher.forward(request, response);
            } else {
                tb = "doi password that bai";
                url = "/doipasswordad.jsp?tb=" + tb;
                RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
                dispatcher.forward(request, response);
            }
            GiaoVien.Close();
        } catch (Exception e) {
            tb = "doi password that bai exception";
            url = "/doipasswordad.jsp?tb=" + tb;
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
            dispatcher.forward(request, response);
        }
        url = "/doipasswordad.jsp?tb=" + tb;
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
        dispatcher.forward(request, response);
    }

    void themGV(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String url = "";
        String tb = "";
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String hoTenGV = request.getParameter("hotengv");
        String khoa = request.getParameter("khoa");
        if (password != null) {
            password = password.trim();
            password = password.replace("  ", " ");
        }
        if (username != null) {
            username = username.trim();
            username = username.replace("  ", " ");
        }
        if (hoTenGV != null) {
            hoTenGV = hoTenGV.trim();
            hoTenGV = hoTenGV.replace("  ", " ");
        }
        if (khoa != null) {
            khoa = khoa.trim();
            khoa = khoa.replace("  ", " ");
        }
        if (password == null || username == null || hoTenGV == null || khoa == null || password.equals("")
                || username.equals("") || password.equals("") || hoTenGV.equals("") || khoa.equals("")
                || password.length() > 32 || username.length() > 15 || hoTenGV.length() > 30 || khoa.length() > 15) {
            tb = "du lieu khong hop le";
            url = "/themgv.jsp?tb=" + tb;
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
            dispatcher.forward(request, response);
        }
        try {
            GiaoVien myGV = new GiaoVien(0, username, password, hoTenGV, khoa, "all", "all");
            GiaoVien.Open();
            if (myGV.insGiaoVien() > 0) {
                tb = "them thanh cong";
            } else {
                tb = "them that bai";
            }
            GiaoVien.Close();
        } catch (Exception e) {
            tb = "them that bai";
            url = "/themgv.jsp?tb=" + tb;
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
            dispatcher.forward(request, response);
        }
        url = "/themgv.jsp?tb=" + tb;
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
        dispatcher.forward(request, response);
    }

    void phanQuyen(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String url = "";
        String tb = "";
        String username = request.getParameter("username");
        String phanQuyenMon = request.getParameter("phanquyenmon");
        String phanQuyenLop = request.getParameter("phanquyenlop");

        if (phanQuyenMon != null) {
            phanQuyenMon = phanQuyenMon.trim();
            phanQuyenMon = phanQuyenMon.replace("  ", " ");
        }
        if (username != null) {
            username = username.trim();
            username = username.replace("  ", " ");
        }
        if (phanQuyenLop != null) {
            phanQuyenLop = phanQuyenLop.trim();
            phanQuyenLop = phanQuyenLop.replace("  ", " ");
        }
        if (phanQuyenLop == null || username == null || phanQuyenMon == null
                || username.equals("") || phanQuyenLop.equals("") || phanQuyenMon.equals("")
                || username.length() > 15) {
            tb = "du lieu khong hop le";
            url = "/phanquyen.jsp?tb=" + tb;
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
            dispatcher.forward(request, response);
        }
        try {

            GiaoVien.Open();
            if (GiaoVien.phanQuyen(username, phanQuyenMon, phanQuyenLop) > 0) {
                tb = "sua thanh cong";
            } else {
                tb = "sua that bai";
            }
            GiaoVien.Close();
        } catch (Exception e) {
            tb = "sua that bai";
            url = "/phanquyen.jsp?tb=" + tb;
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
            dispatcher.forward(request, response);
        }
        url = "/phanquyen.jsp?tb=" + tb;
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
        dispatcher.forward(request, response);
    }

    private void hs_login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String maSV = request.getParameter("masv");
        String hoTenSV = request.getParameter("hoten");
        String ngaySinh = request.getParameter("ngaysinh");
        String lop = request.getParameter("lop");

        try {
            SinhVien sv = SinhVien.ktDangNhap(maSV, hoTenSV, ngaySinh, lop);
            if (sv != null) {
                CaThi ct = CaThi.getCaThiByLogin(lop);
                if (ct == null) {
                    RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/hs_login.jsp");
                    requestDispatcher.forward(request, response);
                }
                BoDeThi boDe = new BoDeThi(ct.getMaMonThi());
                DeThi deThi = DeThi.generateDeThi(ct.getMaMonThi(), ct.getSoCauHoi(), boDe.getListCauHoi());
                deThi.setLanThi(ct.getLanThi());
                HttpSession session = request.getSession();
                session.setAttribute("dethi", deThi);
                session.setAttribute("sinhvien", sv);
                session.setAttribute("cathi", ct);
                if (deThi.saveToDatabase(maSV, ct.getLanThi()) == 403) {
                    response.sendError(403);
                    return;
                }
                RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/hs_lambaithi.jsp");
                requestDispatcher.forward(request, response);
            } else {
                RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/hs_login.jsp");
                requestDispatcher.forward(request, response);
            }

        } catch (SQLException ex) {
            Logger.getLogger(XuLy.class
                    .getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void tinhdiem(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            DeThi deThi = (DeThi) request.getSession().getAttribute("dethi");
            SinhVien sv = (SinhVien) request.getSession().getAttribute("sinhvien");
            int soCau = deThi.getSoCau();
            int soCauDung = 0;
            StringBuilder dsCauTraLoi = new StringBuilder();
            for (int i = 0; i < soCau; i++) {
                String name = "cau" + i;
                String luachon = request.getParameter(name);
                if (luachon == null) {
                    continue;
                }
                dsCauTraLoi.append(luachon + ";");
                if (deThi.getListCauHoi().get(i).getDapAn().equals(luachon)) {
                    soCauDung++;
                }
            }
            if (dsCauTraLoi.length() > 0) {
                dsCauTraLoi.deleteCharAt(dsCauTraLoi.length() - 1);
            }
            String ketqua = new String(dsCauTraLoi);
            response.getWriter().println(ketqua);
            float diem = (float) soCauDung / soCau * 10;
            KetQuaThi kq = new KetQuaThi(sv.getMaSV(), deThi.getMaMonThi(), deThi.getLanThi(), deThi.getDsCauHoi(), ketqua, deThi.getDsDapAn(), diem);
            response.getWriter().println(kq.getDSCauTraloi());
            kq.ghiKetQua();

            request.getSession().setAttribute("diem", diem + "");
            RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/ketquathi.jsp");
            requestDispatcher.forward(request, response);
        } catch (ServletException ex) {
            Logger.getLogger(XuLy.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private boolean isGV(HttpServletRequest request, HttpServletResponse response) {
        GiaoVien gv = (GiaoVien) request.getSession().getAttribute("gv");
        if (gv == null) {
            return false;
        }
        return true;
    }

    private boolean isAD(HttpServletRequest request, HttpServletResponse response) {
        GiaoVien gv = (GiaoVien) request.getSession().getAttribute("gv");
        if (gv == null) {
            return false;
        } else if (!gv.getUsername().equals("admin")) {
            return false;
        }
        return true;
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
